package net.zio.kamenriderzioaddon.procedures;

import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.api.distmarker.Dist;

import net.minecraft.resources.ResourceLocation;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.world.entity.player.Player;

import dev.kosmx.playerAnim.api.layered.AnimationStack;
import dev.kosmx.playerAnim.api.layered.IAnimation;
import dev.kosmx.playerAnim.api.layered.ModifierLayer;
import dev.kosmx.playerAnim.api.layered.KeyframeAnimationPlayer;
import dev.kosmx.playerAnim.core.data.KeyframeAnimation;
import dev.kosmx.playerAnim.minecraftApi.PlayerAnimationAccess;
import dev.kosmx.playerAnim.minecraftApi.PlayerAnimationRegistry;

import java.util.IdentityHashMap;
import java.util.Map;
import javax.annotation.Nullable;

@Mod.EventBusSubscriber(modid = "kamen_rider_zio_addon", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public class SetupAnimationsProcedure {
	public static final Map<AbstractClientPlayer, ModifierLayer<IAnimation>> animationData = new IdentityHashMap<>();

	@SubscribeEvent
	public static void onClientSetup(FMLClientSetupEvent event) {
		// 使用 PlayerAnimationAccess 注册动画工厂
		PlayerAnimationAccess.REGISTER_ANIMATION_EVENT.register(SetupAnimationsProcedure::registerPlayerAnimation);
	}

	private static void registerPlayerAnimation(AbstractClientPlayer player, AnimationStack stack) {
		ModifierLayer<IAnimation> layer = new ModifierLayer<>();
		stack.addAnimLayer(1000, layer);
		animationData.put(player, layer);
	}

	public static void playAnimation(Player player, String animationName, boolean start) {
		if (player instanceof AbstractClientPlayer clientPlayer) {
			ModifierLayer<IAnimation> layer = animationData.get(clientPlayer);
			if (layer != null) {
				if (start) {
					ResourceLocation animId = new ResourceLocation("kamen_rider_zio_addon", animationName);
					KeyframeAnimation animation = PlayerAnimationRegistry.getAnimation(animId);
					if (animation != null) {
						layer.setAnimation(new KeyframeAnimationPlayer(animation));
					}
				} else {
					layer.setAnimation(null);
				}
			}
		}
	}

	public static void stopAnimation(Player player) {
		playAnimation(player, "", false); // 调用 playAnimation 方法停止动画
	}

	// 添加获取动画层的方法
	public static ModifierLayer<IAnimation> getAnimationLayer(Player player) {
		if (player instanceof AbstractClientPlayer clientPlayer) {
			return animationData.get(clientPlayer);
		}
		return null;
	}
}